package web

import (
	"encoding/json"
	"html/template"
	"io"
	"io/fs"

	log "github.com/sirupsen/logrus"
)

func NewIndexHandler(content fs.FS, dev bool) *IndexHandler {
	handler := &IndexHandler{content: content, Dev: dev}

	handler.Init()
	return handler
}

type IndexHandler struct {
	content fs.FS
	Dev     bool
	funcMap template.FuncMap
}

func (h *IndexHandler) Init() {
	h.funcMap = template.FuncMap{
		"manifest": h.readManifest,
	}
}

func (h *IndexHandler) Index(writer io.Writer) error {
	f, err := h.content.Open("index.html")
	if err != nil {
		// ctx.Writer.Write([]byte("读取文件异常：" + err.Error()))
		log.Fatalf("读取文件异常：%v" + err.Error())
		return err
	}
	fileBytes, _ := io.ReadAll(f)
	parameters := make(map[string]interface{})
	parameters["Dev"] = h.Dev
	log.Infof("parameters: %v", parameters)
	t, _ := template.New("test").Funcs(h.funcMap).Parse(string(fileBytes))
	// ctx.Writer.WriteHeader(200)
	t.Execute(writer, parameters)
	return nil
}

func (h *IndexHandler) readManifest(key string, subKey string) string {
	log.Infof("readManifest方法运行: %s, %s", key, subKey)
	f, err := h.content.Open(".vite/manifest.json")
	if err != nil {
		log.Fatalf("open file err %v", err)
		return err.Error()
	}
	datas, _ := io.ReadAll(f)
	dataMap := make(map[string]interface{})
	json.Unmarshal(datas, &dataMap)
	if val, ok := dataMap[key]; ok {
		subMap := val.(map[string]interface{})
		fileKey := subMap[subKey].(string)
		log.Infof("file: %s", fileKey)
		return fileKey
		// return val.(string)
	} else {
		log.Infof("找不到文件: %s", key)
	}
	return "不存subKey: " + subKey
}
